import axios from 'axios';

// API 基础配置
const API_BASE_URL = process.env.REACT_APP_SERVER_BASE_URL || 'http://localhost:3000';
const API_TIMEOUT = 30000; // 30 秒超时

// 创建 axios 实例
const api = axios.create({
    baseURL: API_BASE_URL,
    timeout: API_TIMEOUT,
    headers: {
        'Content-Type': 'application/json'
    }
});

/**
 * 发送消息到 AI 服务
 * @param {string} content - 消息内容
 * @param {function} onStream - 流式响应回调函数
 * @param {boolean} stream - 是否使用流式响应
 * @param {AbortController} abortController - 用于取消请求的控制器
 * @returns {Promise} - 返回响应数据
 */

const formatMarkdown = (content) => {
    // 添加段落间距
    let formatted = content.replace(/\n\n/g, "\n\n\n");

    // 确保列表项之间有适当的间距
    formatted = formatted.replace(/(\n-|\n\d+\.)/g, "\n\n$1");

    // 确保标题前后有适当的间距
    formatted = formatted.replace(/(\n#{1,6}\s)/g, "\n\n$1");

    // 确保代码块前后有适当的间距
    formatted = formatted.replace(/(\n```)/g, "\n\n$1");

    // 移除多余的空行
    formatted = formatted.replace(/\n{4,}/g, "\n\n\n");

    return formatted;
};


/**
 * 发送消息到服务器（Ollama 服务）
 * @param {string} content - 消息内容
 * @param {function} onStream - 流式响应回调函数
 * @param {boolean} stream - 是否使用流式响应
 * @param {AbortController} abortController - 用于取消请求的控制器
 * @returns {Promise} - 返回响应数据
 */
export const sendMessage2ServerBakBak = async (message, onProgress, stream = true, abortController) => {
    try {
        console.log(
            "Request URL:",
            process.env.REACT_APP_SERVER_BASE_URL2 + "/api/v1/chat/stream_chat"
        );

        const requestBody = { content: message };

        console.log("Request body:", JSON.stringify(requestBody, null, 2));

        const response = await fetch(
            process.env.REACT_APP_SERVER_BASE_URL2 + "/api/v1/chat/stream_chat",
            // process.env.REACT_APP_SERVER_BASE_URL + "/api/stream_chat",
            {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(requestBody),
                signal: abortController?.signal,
            }
        );

        console.log("Response status:", response.status);
        console.log(
            "Response headers:",
            Object.fromEntries(response.headers.entries())
        );

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            console.error("API Error Response:", errorData);
            throw new Error(
                `API request failed with status ${response.status}: ${JSON.stringify(
                    errorData
                )}`
            );
        }

        if (!stream) {
            const data = await response.json();
            const formattedContent = formatMarkdown(data);
            onProgress?.(formattedContent);
            return formattedContent;
        }

        const reader = response.body?.getReader();
        if (!reader) {
            throw new Error("Failed to get response reader");
        }

        let fullResponse = "";

        try {
            while (true) {
                // 检查是否被中止
                if (abortController?.signal.aborted) {
                    console.log('Generation aborted during streaming');
                    return null;
                }

                const { done, value } = await reader.read();
                if (done) break;

                const chunk = new TextDecoder().decode(value);
                console.log(chunk);
                fullResponse += chunk;
                onProgress?.(fullResponse);
                // const lines = chunk.split("\n").filter((line) => line.trim());

                // for (const line of lines) {
                //     try {
                //         // const data = JSON.parse(line);
                //         // if (data.response) {
                //         //     fullResponse += data.response;
                //         //     onProgress?.(fullResponse);
                //         // }
                //         fullResponse += line;
                //         onProgress?.(fullResponse);
                //     } catch (e) {
                //         console.warn("Failed to parse chunk:", line);
                //     }
                // }
            }
        } catch (error) {
            if (error instanceof Error && error.name === 'AbortError') {
                console.log('Generation stopped by user during streaming');
                return null;
            }
            throw error;
        }
        console.log(fullResponse);
        console.log(formatMarkdown(fullResponse));
        return formatMarkdown(fullResponse);
    } catch (error) {
        if (error instanceof Error && error.name === 'AbortError') {
            console.log('Generation stopped by user');
            return null;
        }
        console.error("Error sending message to DeepSeek:", error);
        throw error;
    }
};

/**
 * 发送消息到服务器（Ollama 服务）
 * @param {string} content - 消息内容
 * @param {function} onStream - 流式响应回调函数
 * @param {boolean} stream - 是否使用流式响应
 * @param {AbortController} abortController - 用于取消请求的控制器
 * @returns {Promise} - 返回响应数据
 */
export const sendMessage2Server = async (message, onProgress, stream = true, abortController) => {
    try {
        console.log(
            "Request URL:",
            process.env.REACT_APP_SERVER_BASE_URL + "/api/stream_chat"
        );

        const requestBody = { content: message };

        console.log("Request body:", JSON.stringify(requestBody, null, 2));

        const response = await fetch(
            process.env.REACT_APP_SERVER_BASE_URL + "/api/stream_chat",
            {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(requestBody),
                signal: abortController?.signal,
            }
        );

        console.log("Response status:", response.status);
        console.log(
            "Response headers:",
            Object.fromEntries(response.headers.entries())
        );

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            console.error("API Error Response:", errorData);
            throw new Error(
                `API request failed with status ${response.status}: ${JSON.stringify(
                    errorData
                )}`
            );
        }

        if (!stream) {
            const data = await response.json();
            const formattedContent = formatMarkdown(data.response);
            onProgress?.(formattedContent);
            return formattedContent;
        }

        const reader = response.body?.getReader();
        if (!reader) {
            throw new Error("Failed to get response reader");
        }

        let fullResponse = "";

        try {
            while (true) {
                // 检查是否被中止
                if (abortController?.signal.aborted) {
                    console.log('Generation aborted during streaming');
                    return null;
                }

                const { done, value } = await reader.read();
                if (done) break;

                const chunk = new TextDecoder().decode(value);
                const lines = chunk.split("\n").filter((line) => line.trim());

                let buffer = "";

                for (const line of lines) {
                    // 拼接上次未完成的内容
                    let jsonLine = buffer + line;
                    try {
                        const data = JSON.parse(jsonLine);
                        buffer = ""; // 解析成功，清空缓存
                        if (data.response) {
                            fullResponse += data.response;
                            onProgress?.(fullResponse);
                        }
                    } catch (e) {
                        // 解析失败，说明不是完整的 JSON，缓存起来等待下次拼接
                        buffer = jsonLine;
                        // 可以选择不打印警告，或者只在多次失败后打印
                    }
                }
            }
        } catch (error) {
            if (error instanceof Error && error.name === 'AbortError') {
                console.log('Generation stopped by user during streaming');
                return null;
            }
            throw error;
        }

        return formatMarkdown(fullResponse);
    } catch (error) {
        if (error instanceof Error && error.name === 'AbortError') {
            console.log('Generation stopped by user');
            return null;
        }
        console.error("Error sending message to DeepSeek:", error);
        throw error;
    }
};

/**
 * 检查 AI 服务是否可用
 * @returns {Promise<boolean>} - 返回服务是否可用
 */
export const checkService = async () => {
    try {
        await api.get('/api/health');
        return true;
    } catch (error) {
        return false;
    }
};

/**
 * 检查配置
 * @returns {Promise<boolean>} 配置是否有效
 */
export const checkConfig = async () => {
    try {
        const response = await axios.get(`${API_BASE_URL}/config`);
        return response.data.valid;
    } catch (error) {
        console.error('配置检查失败:', error);
        return false;
    }
}; 